package gridmapper.server;

import gridmapper.RobotData;
import gridmapper.RobotDataParser;
import gridmapper.RobotHeading;
import gridmapper.ServerData;
import gridmapper.ServerDataParser;

import java.io.IOException;
import java.util.Scanner;

import lejos.pc.comm.NXTCommFactory;
import lejos.pc.comm.NXTConnector;

public class ConsoleServer extends Thread {

	private NXTConnector getConnector(RobotInfo info) {
		NXTConnector conn = new NXTConnector();
		if (conn.connectTo(info.name, info.address, NXTCommFactory.BLUETOOTH)) 
			return conn;
		return null;
	}

	public static void main(String[] args) {
		System.out.println(System.getProperty("java.library.path"));
		new ConsoleServer().start();
	}

	@Override
	public void run() {
		NXTConnector conn; //CHNAGE THIS!!!
		Scanner scan = new Scanner(System.in);	
		String current;
		
		System.out.println("1. GridMapperServer.RheinoBot ");
		System.out.println("2. GridMapperServer.NXT ");
		System.out.println("Chose your Destiny: ");
		
		if(scan.nextInt() == 1)
		{
			conn = getConnector(GridMapperServer.RheinoBot);
		}
		else
			 conn = getConnector(GridMapperServer.NXT);
		
		if (conn == null) {
			System.err.println("Unable to connect to robot.");
			System.exit(-1);
		}

		System.out.println("Enter a command: (NORTH, SOUTH, EAST, WEST,WAIT, EXIT)");
		while (!(current = scan.next()).equalsIgnoreCase("EXIT")) {
			int heading = RobotHeading.parseRobotHeadings(current);
			if (heading == Integer.MIN_VALUE) {
				System.err.println("Invalid command received.");
				continue;
			}
			RobotData temp;
			RobotDataParser rdp = new RobotDataParser();
			ServerData data = new ServerData(heading, true);
			ServerDataParser sdp = new ServerDataParser();

			System.out.println("Reading data from robot.");
			if (!(temp = rdp.readData(conn.getDataIn())).isErrorFree()) {
				System.err.println("Unable to read data from robot.");
				System.exit(-1);
			}
			System.out.println("Data received " + temp.toString());
			System.out.println("Writing data to robot " + data.toString());
			if (!sdp.writeData(conn.getDataOut(), data)) {
				System.err.println("Unable to write instructions to robot.");
				System.exit(-1);
			}
			System.out
					.println("Enter a command: (NORTH, SOUTH, EAST, WEST, EXIT)");
		}
		
		ServerDataParser sdp = new ServerDataParser();
		ServerData data = new ServerData(360, false);
		if (!sdp.writeData(conn.getDataOut(), data)) {
			System.err.println("Unable to write instructions to robot.");
			System.exit(-1);
		}
		
		try {
			conn.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
